package com.bjpowernode.mvc.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.bjpowernode.common.client.RedisClient;
import com.bjpowernode.common.consts.Keys;
import com.bjpowernode.common.enums.Code;
import com.bjpowernode.mvc.model.response.Response;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.rmi.NotBoundException;


/*拦截器*/
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private RedisClient redisClient;

    public TokenInterceptor(RedisClient redisClient) {
        this.redisClient = redisClient;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //处理option预检请求,放行.
        if ("OPTIONS".equals(request.getMethod())){
            return true;
        }

        //对/ylb/product/detail单独处理
        String productDetailUrl="/ylb/product/detail";
        if (productDetailUrl.equals(request.getRequestURI())&&StrUtil.isBlank(request.getHeader("uid"))){
            return true;
        }

        boolean checkTokenUid=false;
        //从request种获取token和uid
        String authorization =request.getHeader("Authorization");
        if (StrUtil.isNotBlank(authorization)&&authorization.startsWith("Bearer")){
            String token=authorization.substring(7);
            if (StrUtil.isNotBlank(token)){
                //验证redis,判断token的key
                String key= Keys.TOKEN_ACCESS+token.toUpperCase();
                boolean exists=redisClient.hasKey(key);
                if (exists){
                    //有效.
                    String uidInHeader =request.getHeader("uid");
                    if (StrUtil.isNotBlank(uidInHeader)&&uidInHeader.equals(redisClient.getHashField(key,"id"))){
                        checkTokenUid=true;
                    }
                }
            }
        }
        //对验证token的结果做返回前端

        if (!checkTokenUid){
            Response resp=Response.FAIL(Code.TOKEN_INVALID);
          String jsonStr=  JSONUtil.toJsonStr(resp);

          //使用HttpServletResponse输出jsonStr
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer=response.getWriter();
            writer.println(jsonStr);
            writer.flush();
            writer.close();
        }

        return checkTokenUid;
    }
}
